package cn.qicaiwang.open.system.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.qicaiwang.open.common.constant.Constants;
import cn.qicaiwang.open.common.utils.StringUtils;
import cn.qicaiwang.open.system.mapper.SystemMenuMapper;
import cn.qicaiwang.open.system.model.entity.SystemMenu;
import cn.qicaiwang.open.system.model.req.SystemMenuREQ;
import cn.qicaiwang.open.system.model.vo.SystemRouter;
import cn.qicaiwang.open.system.model.vo.SystemRouterMeta;
import cn.qicaiwang.open.system.service.ISystemMenuService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

@Service
public class SystemMenuService extends ServiceImpl<SystemMenuMapper, SystemMenu> implements ISystemMenuService {
    @Autowired
    private SystemMenuMapper systemMenuMapper;

    @Override
    public Page<SystemMenu> pageList(Page page, SystemMenuREQ params) {
        return systemMenuMapper.page(page, params);
    }

    @Override
    public List<SystemMenu> selectListByUserId(String id) {
        return systemMenuMapper.selectListByUserId(id);
    }

    @Override
    public List<SystemRouter> getRouters(String rolePerm) {
        List<SystemMenu> systemMenus = new ArrayList<>();
        if(Constants.SUPER_ADMIN_ROLE.equals(rolePerm)){
            QueryWrapper<SystemMenu> queryWrapper = new QueryWrapper<SystemMenu>();
            queryWrapper.ne("type", 2);
            queryWrapper.eq("enabled",1);
            queryWrapper.orderByAsc("parent_id","sort");
            systemMenus = systemMenuMapper.selectList(queryWrapper);
        }else{
            systemMenus = systemMenuMapper.selectListByRolePerm(rolePerm);
        }
        List<SystemMenu> childPerms = getChildPerms(systemMenus, "-1");

        List<SystemRouter> routers = buildRouters(childPerms);
        return routers;
    }

    private List<SystemRouter> buildRouters(List<SystemMenu> systemMenus){
        List<SystemRouter> routers = new LinkedList<SystemRouter>();
        for (SystemMenu systemMenu: systemMenus) {
            SystemRouter router = new SystemRouter();
            router.setId(systemMenu.getId());
            router.setName(systemMenu.getName());
            router.setPath(systemMenu.getPath());
            router.setParentView(systemMenu.getParentView());
            router.setComponent(systemMenu.getComponent());
            router.setQuery(systemMenu.getQuery());
            router.setType(systemMenu.getType());
            router.setRedirect(systemMenu.getRedirect());

            SystemRouterMeta meta = SystemRouterMeta.builder()
                    .title(systemMenu.getName())
                    .icon(systemMenu.getIcon())
                    .noCache(systemMenu.getCache() == 1)
                    .hidden(systemMenu.getVisible() == 1)
                    .link(StringUtils.ishttp(systemMenu.getPath()) ? systemMenu.getPath() : "")
                    .affix(systemMenu.getAffix() == 1)
                    .build();

            router.setMeta(meta);
            List<SystemMenu> cMenus = systemMenu.getChildren();
            if (!cMenus.isEmpty() && Constants.TYPE_DIR.equals(systemMenu.getType())) {
                router.setAlwaysShow(true);
                router.setChildren(buildRouters(cMenus));
            }
            routers.add(router);
        }
        return routers;
    }

    /**
     * 根据父节点的ID获取所有子节点
     *
     * @param list     分类表
     * @param parentId 传入的父节点ID
     * @return String
     */
    public List<SystemMenu> getChildPerms(List<SystemMenu> list, String parentId) {
        List<SystemMenu> returnList = new ArrayList<SystemMenu>();
        for (Iterator<SystemMenu> iterator = list.iterator(); iterator.hasNext(); ) {
            SystemMenu t = iterator.next();
            // 一、根据传入的某个父节点ID,遍历该父节点的所有子节点
            if (t.getParentId().equals(parentId)) {
                recursionFn(list, t);
                returnList.add(t);
            }
        }
        return returnList;
    }

    /**
     * 递归列表
     *
     * @param list
     * @param t
     */
    private void recursionFn(List<SystemMenu> list, SystemMenu t) {
        // 得到子节点列表
        List<SystemMenu> childList = getChildList(list, t);
        t.setChildren(childList);
        for (SystemMenu tChild : childList) {
            if (hasChild(list, tChild)) {
                recursionFn(list, tChild);
            }
        }
    }

    /**
     * 得到子节点列表
     */
    private List<SystemMenu> getChildList(List<SystemMenu> list, SystemMenu t) {
        List<SystemMenu> tlist = new ArrayList<SystemMenu>();
        Iterator<SystemMenu> it = list.iterator();
        while (it.hasNext()) {
            SystemMenu n = it.next();
            if (n.getParentId().equals(t.getId())) {
                tlist.add(n);
            }
        }
        return tlist;
    }

    /**
     * 判断是否有子节点
     */
    private boolean hasChild(List<SystemMenu> list, SystemMenu t) {
        return CollUtil.isNotEmpty(getChildList(list, t));
    }


    @Override
    public Page<SystemMenu> recyclebin(Page page) {
        return systemMenuMapper.recyclebin(page);
    }
    @Override
    public Boolean restore(List<String> ids) {
        int counter = 0;
        for (int i = 0; i < ids.size(); i++) {
            counter += systemMenuMapper.restore(ids.get(i));
        }
        return counter > 0;
    }

    @Override
    public Boolean clear() {
        return systemMenuMapper.clear() > 0;
    }
}
